<template>
  <div class="">
    <a-spin :loading="spinLoading" :tip="spinTip" dot style="width: 100%;">
      <a-card class="custom-card">
        <div ref="searchRef">

        </div>
        <div class="table-header lg:flex justify-between mb-2">
          <a-breadcrumb>
            <a-breadcrumb-item v-for="(breadcrumb, index) in breadcrumbs" :key="index">
              <a-link :hoverable="false" @click="viewFloder(breadcrumbs[index].path)">
                <span v-if="!breadcrumbs[index].name"><icon-home /></span>
                <span v-else>{{ breadcrumbs[index].name }}</span>
              </a-link>
            </a-breadcrumb-item>
          </a-breadcrumb>
        </div>
        <div ref="tableContainerRef">
          <a-table
            ref="tableRef"
            row-key="id"
            :loading="loading"
            :pagination="false"
            :data="renderData"
            :bordered="{ wrapper: true, cell: true }"
            :row-selection="rowSelection"
            :scroll="tableScroll"
            column-resizable
          >
            <template #columns>
              <a-table-column title="名称" data-index="name" :width="200">
                <template #cell="{ record }">
              <span v-if="record.link">
                <a-link :hoverable="false" @click="viewFloder(record.link)"><i :class="record.icon"></i> {{ record.name }}</a-link>
              </span>
                  <span v-else><i :class="record.icon"></i> {{ record.name }}</span>
                </template>
              </a-table-column>
              <a-table-column title="大小" data-index="filesize" align="center" :width="100"/>
              <a-table-column title="时间" data-index="modif" align="center" :width="160"/>
              <a-table-column title="属性" data-index="perms" align="center" :width="100"/>
              <a-table-column title="所有者" data-index="owner" align="center" :width="100">
                <template #cell="{ record }">
                  {{ record.owner.name }}:{{ record.group.name }}
                </template>
              </a-table-column>
              <a-table-column title="操作" data-index="operations" align="center" fixed="right" :width="240">
                <template #cell="{ record }">
                  <a-space>
                    <a-button v-if="!record.link" type="primary" size="small" @click="handle(record, 'view')"><template #icon><icon-eye /></template>查看</a-button>
                    <a-button type="primary" status="warning" size="small" @click="handle(record, 'rename')"><template #icon><icon-edit /></template>重命名</a-button>
                    <a-popconfirm content="确定要删除据吗？" type="warning" position="br" @ok="handle(record, 'delete')">
                      <a-button type="primary" status="danger" size="small"><template #icon><icon-delete /></template>删除</a-button>
                    </a-popconfirm>
                  </a-space>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </div>
        <div class="table-footer mt-2">
          <div v-show="!loading" class="total-text">
            文件总大小：<a-tag color="#f53f3f">{{ stateObj.all_files_size }}</a-tag>
            文件数：<a-tag color="#eb0aa4">{{ stateObj.num_files }}</a-tag>
            文件夹数：<a-tag color="#7bc616">{{ stateObj.num_folders }}</a-tag>
            分区大小：<a-tag color="#0fc6c2">{{ stateObj.partition_size }}</a-tag>
            剩余大小：<a-tag color="#168cff">{{ stateObj.free_of_size }}</a-tag>
          </div>
        </div>
      </a-card>
    </a-spin>

    <a-modal
      v-model:visible="renameDialogVisible"
      :title="renameDialogTitle"
      :mask-closable="false"
      @before-ok="renameDialogBeforeOk"
    >
      <a-form ref="renameFormRef" :model="renameData">
        <a-form-item
          field="name"
          label="名称"
          required
          :validate-trigger="['change','input']"
          :rules="[
            {
              required: true,
              message: '名称不能为空',
            },
          ]"
        >
          <a-input v-model="renameData.name" placeholder="请输入名称" style="width: 80%"/>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      v-model:visible="viewDialogVisible"
      :modal-style="modalstyle"
      :body-style="bodystyle"
      :title="viewDialogTitle"
      :mask-closable="false"
    >
      <PreviewCode ref="codeRef" :code-value="fileText" :lang-type="codeLangType"/>
    </a-modal>
  </div>
</template>

<script setup>
  import { ref, reactive, h, compile, nextTick, onMounted, onUnmounted } from 'vue';
  import { Message, Modal } from '@arco-design/web-vue';

  import useLoading from '@/hooks/loading';
  import { workAreaHeight } from '@/utils/index';
  import { apiList, apiHandle } from '@/api/system-file';
  import PreviewCode from '@/components/prism/index.vue';

  const { loading, setLoading } = useLoading(false);
  const renderData = ref([]);
  const tableScroll = ref({
    x: '100%',
    y: '100%',
  });
  const modalstyle = {
    width: '50%',
    height: '65%',
  };
  const bodystyle = {
    height: 'calc(100% - 108px)',
    overflow: 'auto',
  };

  const searchRef = ref();
  const showSearch = ref(true);
  const tableContainerRef = ref();
  const tableRef = ref();
  const searchHeight = ref(0);

  const spinLoading = ref(false);
  const spinTip = ref();

  const renameFormRef = ref();
  const renameData = ref({
    from_name: '',
    name: '',
  });
  const renameDialogVisible = ref(false);
  const renameDialogTitle = ref();
  const viewDialogVisible = ref(false);
  const viewDialogTitle = ref();
  const breadcrumbs = ref([]);

  const stateObj = {
    path: '',
    breadcrumbs: [],
    all_files_size: 0,
    num_files: 0,
    num_folders: 0,
    partition_size: 0,
    free_of_size: 0,
  };
  const codeRef = ref();
  const fileText = ref('');
  const codeLangType = 'php';

  const settingFixedPage = () => {
    const workHeight = workAreaHeight(120);
    const tableHeight = workHeight - searchHeight.value;
    tableContainerRef.value.style.height = `${tableHeight}px`;
  };
  const resizeHandler = () => {
    searchHeight.value = searchRef.value.offsetHeight;
    settingFixedPage();
  };
  const toggleSearch = async () => {
    const dom = searchRef.value?.style;
    if (dom) {
      showSearch.value = !showSearch.value;
      await nextTick(() => {
        searchHeight.value = searchRef.value.offsetHeight;
        settingFixedPage();
      });
    }
  };
  const setTableColumns = () => {

  };

  // 列表
  const fetchData = async (
    params = { path: stateObj.path }
  ) => {
    setLoading(true);
    try {
      const { data } = await apiList(params);
      renderData.value = data.data;
      breadcrumbs.value = data.breadcrumbs;
      stateObj.path = data.path;
      // stateObj.breadcrumbs = data.breadcrumbs;
      stateObj.all_files_size = data.all_files_size;
      stateObj.num_files = data.num_files;
      stateObj.num_folders = data.num_folders;
      stateObj.partition_size = data.partition_size;
      stateObj.free_of_size = data.free_of_size;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  // 查看文件夹/返回目录
  const viewFloder = async (path) => {
    stateObj.path = path;
    await fetchData();
  };
  // 操作
  const handle = async (row, type) => {
    if (type === 'view') {
      // 查看
      setLoading(true);
      try {
        const { data } = await apiHandle({
          path: stateObj.path,
          action: type,
          name: row.name,
        });
        viewDialogVisible.value = true;
        viewDialogTitle.value = row.name;
        stateObj.dialogTitle = row.name;
        // fileText.value = data;
        codeRef.value.fetchData(data);
        await nextTick(() => {
          codeRef.value.highlightAll();
        });
      } catch (err) {
        setLoading(false);
      } finally {
        setLoading(false);
      }
    } else if (type === 'rename') {
      // 重命名
      renameDialogVisible.value = true;
      renameDialogTitle.value = `重命名: ${row.name}`;
      renameData.value.name = row.name;
      renameData.value.from_name = row.name;
    } else if (type === 'delete') {
      // 删除
      setLoading(true);
      try {
        await apiHandle({
          path: stateObj.path,
          action: type,
          name: row.name,
        });
        await fetchData();
      } catch (err) {
        setLoading(false);
      } finally {
        setLoading(false);
      }
    }
  };
  const renameSubmit = async (done) => {
    try {
      const ruleRes = await renameFormRef.value?.validate();
      if (!ruleRes) {
        await apiHandle({
          path: stateObj.path,
          action: 'rename',
          from_name: renameData.value.from_name,
          name: renameData.value.name,
        });
        done();
        await fetchData();
      } else {
        done(false);
      }
    } catch (err) {
      done(false);
    } finally {
      done(false);
    }
  };

  const renameDialogBeforeOk = (done) => {
    renameSubmit(done);
  };

  onMounted(async () => {
    await fetchData();
    window.addEventListener('resize', resizeHandler, false);
    searchHeight.value = searchRef.value.offsetHeight;
    settingFixedPage();
  });
  onUnmounted(() => {
    window.removeEventListener('resize', resizeHandler, false);
  });
</script>

<script>
  export default {
    name: 'SystemFile',
  };
</script>

<style scoped lang="less">
  @import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css');

  .total-text {
    border-left: 1px solid #dfe6ec;
    border-right: 1px solid #dfe6ec;
    border-bottom: 1px solid #dfe6ec;
    height: 35px;
    line-height: 35px;
    padding-left: 10px;
    font-size: 14px;
    color: #606266;
  }

  i.fa.fa-folder-o {
    color: #0157b3
  }
  i.fa.fa-picture-o {
    color: #26b99a
  }
  i.fa.fa-file-archive-o {
    color: #da7d7d
  }
  i.fa.fa-css3 {
    color: #f36fa0
  }
  i.fa.fa-file-code-o {
    color: #007bff
  }
  i.fa.fa-code {
    color: #cc4b4c
  }
  i.fa.fa-file-text-o {
    color: #0096e6
  }
  i.fa.fa-html5 {
    color: #d75e72
  }
  i.fa.fa-file-excel-o {
    color: #09c55d
  }
  i.fa.fa-file-powerpoint-o {
    color: #f6712e
  }
</style>
